<template>
  <div>
    <el-drawer
      :title="action === 'add' ? '新增秒杀' : '编辑秒杀'"
      :before-close="handleClose"
      :visible="addOrEditDialog"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      size="50%"
    >
      <div class="demo-drawer__content">
        <el-form
          :model="form"
          label-position="top"
          :rules="formRules"
          ref="ruleForm"
        >
          <el-form-item
            label="活动名称"
            :label-width="formLabelWidth"
            prop="activityName"
          >
            <el-input
              v-model="form.activityName"
              type="text"
              autocomplete="off"
              size="small"
              maxlength="21"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item
            label="开始时间"
            :label-width="formLabelWidth"
            prop="startTime"
          >
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="选择开始时间"
              size="small"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="结束时间"
            :label-width="formLabelWidth"
            prop="endTime"
          >
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="选择结束时间"
              size="small"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>

          <!-- 添加优惠券 -->
          <el-form-item label="" :label-width="formLabelWidth">
            <el-button type="primary" @click="handleAddCouponBtn"
              >添加优惠券</el-button
            >
            <!-- 已选择的优惠券 -->
            <el-table
              :data="currentCouponList"
              style="width: 100%"
              v-loading="couponLoading"
            >
              <el-table-column prop="couponRemark" label="名称" width="180">
              </el-table-column>
              <el-table-column prop="couponAmt" label="面额" width="180">
              </el-table-column>
              <el-table-column
                prop="couponThresholdAmt"
                label="门槛"
                :formatter="couponThresholdAmtFormat"
              >
              </el-table-column>
              <el-table-column prop="address" label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    @click="removeOneCoupon(scope.row, scope.$index)"
                    size="small"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item
            label="库存"
            :label-width="formLabelWidth"
            prop="originStock"
          >
            <el-input
              v-model="form.originStock"
              autocomplete="off"
              size="small"
              type="number"
              placeholder="请输入"
            ></el-input>
          </el-form-item>

          <el-form-item label="售价" :label-width="formLabelWidth" prop="price">
            <el-input
              v-model="form.price"
              autocomplete="off"
              size="small"
              show-word-limit
              placeholder="请输入"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="原价"
            :label-width="formLabelWidth"
            prop="originalPrice"
          >
            <el-input
              v-model="form.originalPrice"
              autocomplete="off"
              size="small"
              show-word-limit
              placeholder="请输入"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="描述"
            :label-width="formLabelWidth"
            prop="description"
          >
            <el-input
              v-model="form.description"
              type="textarea"
              autocomplete="off"
              size="small"
              placeholder="请输入"
              maxlength="64"
              show-word-limit
              :clearable="true"
              :row="2"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="最大购买次数，0为不限制"
            :label-width="formLabelWidth"
            prop="maxBuyNum"
          >
            <el-input
              v-model="form.maxBuyNum"
              type="number"
              autocomplete="off"
              size="small"
              show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="商品图片" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="imgUpConfig.addressUrl"
              :headers="imgUpConfig.headers"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div v-if="imageUrl" class="icon-delete" @click="removeImg">
                <i class="el-icon-delete"></i>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png格式的图片文件,图片不超过10M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="submitForm">
            {{ loading ? "提交中 ..." : "确 定" }}
          </el-button>
        </div>

        <!-- 当前所有的优惠券列表
          v-if="refresh"

        -->
        <el-dialog
          :visible.sync="conponDialogVisible"
          title="选择优惠券"
          class="allCouponlist"
          :append-to-body="true"
          @close="handleCloseDialog"
        >
          <el-table
            ref="multipleTable"
            :data="AllCouponList"
            tooltip-effect="dark"
            style="width: 100%; height: 70vh; overflow-y: auto"
            :modal="false"
            @selection-change="handleSelectionChange"
            :row-key="getRowkey"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
              :reserve-selection="true"
            >
            </el-table-column>
            <el-table-column prop="couponRemark" label="名称">
            </el-table-column>
            <el-table-column prop="couponAmt" label="面额" width="130">
            </el-table-column>
            <el-table-column
              prop="couponThresholdAmt"
              label="门槛"
              show-overflow-tooltip
              width="130"
              :formatter="couponThresholdAmtFormat"
            >
            </el-table-column>
          </el-table>
        </el-dialog>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { creationList } from "@/api/coupon";
import { cloneDeep } from "lodash";
import {
  addOrEditKillActivityApi,
  getKillActivityDetailApi,
} from "@/api/market/secondKill";
export default {
  name: "addOrEdit",
  props: {
    addOrEditDialog: {
      type: Boolean,
      default: false,
    },
    action: {
      type: String,
      default: "add",
    },
    currentRowData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    // 校验数量
    let validateNum = (rule, value, callback) => {
      console.log(1111, value, typeof value);
      let number = Number(value);
      const reg = /^\d+(\.\d{0,0})?$/; // 整数
      if (!String(value)) return callback(new Error("请输入有效值"));
      if (String(value).length > 10)
        return callback(new Error("最大长度为10位"));
      if (!reg.test(number)) return callback(new Error("请输入整数"));
      if (number < 0) return callback(new Error("要大于0"));
      if (number === 0) {
        if (rule.field === "originStock") {
          return callback(new Error("不能等于0"));
        }
      }
      callback();
    };

    // 校验金额
    let validatePrice = (rule, value, callback) => {
      console.log("校验价格：", value);
      const reg = /^\d+(\.\d{0,2})?$/; // 两位小数点
      let amt = Number(value);
      if (!String(value) || value === undefined) {
        if (rule.field === "originalPrice") {
          // 原价可以填空
          callback();
        } else {
          return callback(new Error("请输入数值或有效值"));
        }
      }
      if (value && String(value).startsWith("."))
        return callback(new Error("请输入数值或有效值"));
      if (amt < 0) return callback(new Error("不能小于0"));
      if (String(value).length > 10)
        return callback(new Error("最大长度为10位"));
      if (!reg.test(amt)) return callback(new Error("最多两位小数点"));

      callback();
    };

    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      formLabelWidth: "80px",
      form: {
        maxBuyNum: 0,
      },
      loading: false,
      couponLoading: false,
      currentCouponList: [], // 当前选中的优惠券列表
      tempAllCouponList: [], // 临时存放所有优惠券列表
      AllCouponList: [], // 所有优惠券列表
      imageUrl: "",
      conponDialogVisible: false, // 优惠券弹框
      refresh: false, // 是否刷新dialog
      imgUpConfig: {
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        addressUrl: process.env.VUE_APP_BASE_API + "/common/upload",
        limit: 1,
      },
      formRules: {
        activityName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "选择开始时间", trigger: "blur" },
        ],
        endTime: [{ required: true, message: "选择结束时间", trigger: "blur" }],
        originStock: [
          { required: true, validator: validateNum, trigger: "blur" },
        ],
        price: [{ required: true, validator: validatePrice, trigger: "blur" }],
        originalPrice: [{ validator: validatePrice, trigger: "blur" }],
        maxBuyNum: [
          { required: true, validator: validateNum, trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    addOrEditDialog(val) {
      if (val) {
        this.form = { ...this.currentRowData };
        this.getCouponList();
        if (this.action === "edit") {
          this.getInfoDetail();
        }
      }
    },
  },
  methods: {
    // 关闭抽屉
    handleClose() {
      this.$emit("update:addOrEditDialog", false);
      this.currentCouponList = [];
      this.imageUrl = "";
    },
    // 删除已选中的优惠券
    removeOneCoupon(row, index) {
      this.currentCouponList.splice(index, 1);
    },

    // 图片上传前的校验
    beforeAvatarUpload(file) {
      console.log(file);
      const types = ["image/jpeg", "image/png", "image/jpg"];
      const isLt1M = file.size / 1024 / 1024 < 10;
      if (!isLt1M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
        return false;
      }
      if (!types.includes(file.type)) {
        this.$message.error("图片只能上传png/jpg格式");
        return false;
      }
      return isLt1M;
    },

    // 图片上传成功
    handleAvatarSuccess(response, file, fileList) {
      this.imageUrl = response.url;
      this.form.productImg = response.url;
    },
    // 删除图片
    removeImg(e) {
      e.stopPropagation();
      this.imageUrl = "";
    },

    // 根据id获取活动详情，进行数据回显
    async getInfoDetail() {
      this.couponLoading = true;
      let id = this.currentRowData.id;
      const res = await getKillActivityDetailApi(id);
      this.currentCouponList = res.data.couponList;
      this.imageUrl = res.data.productImg;
      this.couponLoading = false;
    },

    // 点击添加优惠券按钮
    handleAddCouponBtn() {
      this.AllCouponList = this.tempAllCouponList;
      this.conponDialogVisible = true;
      this.refresh = true;
      this.reShow();
    },
    // 数据回显
    reShow() {
      let arr = [];
      arr = this.currentCouponList.map((ele) => ele.id);
      this.$nextTick(() => {
        this.AllCouponList.forEach((ele) => {
          if (arr.includes(ele.id)) {
            this.$refs.multipleTable.toggleRowSelection(ele, true);
          }
        });
      });
    },

    // 优惠券门槛格式化
    couponThresholdAmtFormat(row) {
      // 优惠券类型  1现金券 2折扣券 3 4洗车券
      if (row.couponType === "4" || row.couponThresholdAmt === null) {
        return "---";
      } else {
        return row.couponThresholdAmt;
      }
      // return row.couponType === "4" ? "---" : row.couponThresholdAmt;
    },

    // 关闭选择优惠券的dialog
    handleCloseDialog() {
      let data = cloneDeep(this.currentCouponList);
      this.$refs.multipleTable.clearSelection();
      this.couponLoading = false;
      this.currentCouponList = data;
      this.refresh = false;
    },
    // 提交表单
    submitForm() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const params = { ...this.form };
          params.id = this.action === "add" ? null : this.currentRowData.id;
          params.productImg = this.imageUrl ? this.imageUrl : "";
          params.activityEnable =
            this.action === "add" ? 1 : this.currentRowData.activityEnable;
          params.couponList = this.currentCouponList;
          await addOrEditKillActivityApi(params);
          this.loading = false;
          let message =
            this.action === "add" ? "新增秒杀活动成功" : "编辑秒杀活动成功";
          this.msgSuccess(message);
          this.handleClose();
          this.$emit("reloadData");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 获取优惠券列表
    async getCouponList() {
      // const params = { ...this.queryParams };
      const params = {};
      params.status = 1;
      let res = await creationList(params);
      this.tempAllCouponList = res.rows;
      this.total = res.total;
    },
    // 表格选择行
    handleSelectionChange(list) {
      const _this = this;
      this.currentCouponList = list;
      this.form.couponList = list;
    },

    // 当前行的唯一id
    getRowkey(row) {
      return row.id + "";
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .demo-drawer {
  overflow: auto;
  .el-drawer__header {
    border-bottom: 1px solid #ddd;
    padding-bottom: 15px;
  }
  .el-drawer__body {
    padding: 15px;
    .allCouponlist {
      .el-dialog {
        max-height: 80vh;
        overflow: auto;
      }
    }
    .demo-drawer__content {
      .demo-drawer__footer {
        text-align: end;
      }
    }
    .el-pagination {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      .el-pagination__jump,
      .btn-next,
      .el-pager,
      .btn-prev {
        margin-bottom: 10px;
      }
    }
  }
  // 图片
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  // 删除图像
  .icon-delete {
    position: absolute;
    background: rgba(0, 0, 0, 0.5);
    width: 100%;
    height: 100%;
    top: 0;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    color: #f8f8f8;
    display: none;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
    .icon-delete {
      display: flex;
    }
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
